package com.zbj.storm.wordcount;

import org.apache.storm.task.OutputCollector;
import org.apache.storm.task.TopologyContext;
import org.apache.storm.topology.OutputFieldsDeclarer;
import org.apache.storm.topology.base.BaseRichBolt;
import org.apache.storm.tuple.Fields;
import org.apache.storm.tuple.Tuple;
import org.apache.storm.tuple.Values;

import java.util.Map;

/**
 * SplitLineBolt
 *
 * @author weigang
 * @create 2019-09-04
 **/
public class SplitLineBolt extends BaseRichBolt {

    private OutputCollector collector;

    @Override
    public void prepare(Map<String, Object> topoConf, TopologyContext context, OutputCollector collector) {
        this.collector = collector;
    }

    @Override
    public void execute(Tuple input) {
        try {
            // 从tuple中获取封装信息
            String line = input.getStringByField("line");
            String[] words = line.split(" ");

            // 转换成tuple继续发送数据
            for (int i = 0; i < words.length; i++) {
                collector.emit(input, new Values(words[i]));
            }

            // 向Storm报告成功
            collector.ack(input);
        } catch (Exception e) {
            // 向Storm报告失败
            collector.fail(input);
        }
    }

    @Override
    public void declareOutputFields(OutputFieldsDeclarer declarer) {
        declarer.declare(new Fields("word"));
    }
}